package com.list88zhu.android.sunflower.api;

import android.support.v4.util.ArrayMap;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import retrofit2.Retrofit;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/8
 */
public class ApiProxy {

    private Retrofit retrofit;
    private Lock lock = new ReentrantLock();
    private final ArrayMap<Class, Object> apiCache;

    public ApiProxy(Retrofit retrofit) {
        apiCache = new ArrayMap<>();
        this.retrofit = retrofit;
    }

    public <T> T create(Class<T> cls) {
        Object service = apiCache.get(cls);
        if(service == null) {
            lock.lock();
            service = retrofit.create(cls);
            apiCache.put(cls, service);
            lock.unlock();
        }
        return (T) service;
    }

    public <T> RequestBuilder<T> createBuilder(RequestBuilder.Adapter<T> adapter) {
        return new RequestBuilder<>(adapter);
    }
}
